package com.eco.fanliapp.job.userjob;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.entity.SyUserWxContrast;
import com.eco.fanliapp.service.IAppWxWithdrawalService;
import com.eco.fanliapp.service.ISyUserWxContrastService;
import com.eco.fanliapp.service.WeixinUtil;
import com.eco.fanliapp.utils.DateFormatUtils;
import net.sf.json.JSONObject;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户关注公众号openId处理
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class HandleOpenIdTask implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(HandleOpenIdTask.class);

    @Autowired
    private ISyUserWxContrastService syUserWxContrastService;
    @Autowired
    private IAppWxWithdrawalService appWxWithdrawalService;

    public HandleOpenIdTask() {
    }

    @Override
    public void execute(JobExecutionContext context)   {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap =  jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行用户关注公众号openId处理任务-HandleOpenIdTask：executeCount="+executeCount+"--startTime="+startTime);

        try {
            String nowDate = DateFormatUtils.getCurrentDate();
            QueryWrapper<SyUserWxContrast> queryWrapper = new QueryWrapper<>();
            queryWrapper.isNotNull("wx_opend_id");
//        queryWrapper.ne("wx_opend_id","");
            queryWrapper.eq("enable",true);
            queryWrapper.eq("deleted",false);
            List<SyUserWxContrast> listWxContrast = syUserWxContrastService.list(queryWrapper);

            //提取出已经关注的openId
            List<String> removeList = new ArrayList<>();
            for (SyUserWxContrast wxContrast : listWxContrast){
                removeList.add(wxContrast.getWxOpendId());
            }

            //获取accss_token
            String accessToken = appWxWithdrawalService.getAccessToken();
            log.info("获取access_token:" + accessToken);
            //获取该公众号下所有openIdList
            List<String> openIdList = WeixinUtil.getOpenIdList(accessToken);
            if(openIdList == null || openIdList.size() <= 0){
                log.info(nowDate + "公众号关注人数为0");
                return;
            }
            //提取出新关注公众号的用户
            openIdList.removeAll(removeList);

            //遍历openIdList，获取用户信息
            for (String str : openIdList){
                    log.info("==========请求公众号所有关注的用户列表{}",str);
                    JSONObject userInfo = WeixinUtil.getUserInfo(accessToken, str);
                    String openId = userInfo.getString("openid");
                    String wxUnionid = userInfo.getString("unionid");

                    //保存之前，判断该用户的unionId和openId是否存在
                    QueryWrapper<SyUserWxContrast> wrapper = new QueryWrapper<>();
                    wrapper.ne("union_id",wxUnionid);
                    queryWrapper.eq("enable",true);
                    queryWrapper.eq("deleted",false);
                    List<SyUserWxContrast> listConstrast = syUserWxContrastService.list(wrapper);
                    if(listConstrast != null && listConstrast.size()>0){
                        log.info("openId已经存在：" +openId);
                        continue;
                    }
                    log.info("获取unionId为：" + wxUnionid + " 对应的openId：" + openId);
                    SyUserWxContrast contrast = new SyUserWxContrast();
                    contrast.setUnionId(wxUnionid);
                    contrast.setWxOpendId(openId);
                    syUserWxContrastService.save(contrast);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info("处理用户公众号下openId映射错误");
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行w用户关注公众号openId处理任务-HandleOpenIdTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }
}
